/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import static controller.BusControl.getApplications;
import docs.InternshipCompanyModel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpSession;
import model.Applications;
import model.Student;
import org.netbeans.xml.schema.elements.APPLICATION;
import org.netbeans.xml.schema.elements.APPLICATIONTYPE;
import org.netbeans.xml.schema.elements.COMPANYTYPE;
import org.netbeans.xml.schema.elements.LISTIDTYPE;
import org.netbeans.xml.schema.elements.NOTIFSTYPE;
import org.netbeans.xml.schema.elements.STUDENTTYPE;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Class use to manage the internship actions
 * @author metbill
 */
@Controller
public class CandidatureController {
    
     /**
      * Apply for internship
      * @param internSelected
      * @param model
      * @param session
      * @return 
      */
    @RequestMapping(value = "/applications", method = RequestMethod.GET)
    public String applyInternship (@ModelAttribute("SpringWeb")docs.InternshipCompanyModel internSelected, ModelMap model , HttpSession session) {
        if (session.getAttribute("userID") != null ){ 
            int idUser = (int) session.getAttribute("userID");
            int id = internSelected.getInternshipID();
            List<docs.ApplicationModel> applications = BusControl.getAppListForCompany(id);
            model.addAttribute("applications", applications);
            
            List<InternshipCompanyModel> offers = BusControl.getOffers(null);
            model.addAttribute("offers", offers); 
            Utils.drawHomePage(session.getAttribute("userName").toString(), BusControl.getNotifications(idUser).getNOTIFS().size(),  "candidatureCompany", "internshipsCompany",  model);            
            
            return "home";
        } else {
            model.addAttribute("errormessage", " You need to be authenticated. ");
            return "connection";
        }
     
    }
    
    /**
     * Accept an internship application
     * @param Appl
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/accept", method = RequestMethod.GET)
    public String AcceptApplication (@ModelAttribute("SpringWeb")docs.ApplicationModel Appl, ModelMap model , HttpSession session) {
        if (session.getAttribute("userID") != null ){
           int idUser = (int) session.getAttribute("userID");
            int id = Appl.getInternshipID();
            int idAppl = Appl.getApplicationID();
            BusControl.updateApplicationStatus(6, idAppl);
            List<docs.ApplicationModel> applications = BusControl.getAppListForCompany(id);
            model.addAttribute("applications", applications);
            
            List<InternshipCompanyModel> offers = BusControl.getOffers(null);
            model.addAttribute("offers", offers); 
            
            Utils.drawHomePage(session.getAttribute("userName").toString(), BusControl.getNotifications(idUser).getNOTIFS().size(),  "candidatureCompany", "internshipsCompany", model);            
                        
            return "home";
        } else {
            model.addAttribute("errormessage", " You need to be authenticated. ");
            return "connection";
        }
    }
    
    
    /**
     * Refuse an internship application
     * @param Appl
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/refuse", method = RequestMethod.GET)
    public String RefuseApplication (@ModelAttribute("SpringWeb")docs.ApplicationModel Appl, ModelMap model , HttpSession session) {
        if (session.getAttribute("userID") != null ){
            int idUser = (int) session.getAttribute("userID");
            int id = Appl.getInternshipID();
            int idAppl = Appl.getApplicationID();
            BusControl.updateApplicationStatus(3, idAppl);
            
            List<docs.ApplicationModel> applications = BusControl.getAppListForCompany(id);
            model.addAttribute("applications", applications);
            
            List<InternshipCompanyModel> offers = BusControl.getOffers(null);
            model.addAttribute("offers", offers); 
            
            Utils.drawHomePage(session.getAttribute("userName").toString(), BusControl.getNotifications(idUser).getNOTIFS().size(),  "candidatureCompany", "internshipsCompany", model);            
                        
            return "home";
        } else {
            model.addAttribute("errormessage", " You need to be authenticated. ");
            return "connection";
        }
    }
    
    
    /**
     * 
     * @param Appl
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/acceptSup", method = RequestMethod.GET)
    public String AcceptApplicationSup (@ModelAttribute("SpringWeb")Applications Appl, ModelMap model , HttpSession session) {
        if (session.getAttribute("userID") != null ){
            int idAppl = Appl.getApplicationId();
            //System.out.println("Application ID=" + idAppl);
            
            //Changer le status de l'application => 10
            BusControl.updateApplicationStatus(10, idAppl);
            
            NOTIFSTYPE test = BusControl.getNotifications((int) session.getAttribute("userID"));
            int notifs = test.getNOTIFS().size();
            
            int idStu = Appl.getStudentId();
            //System.out.println("Student ID=" + idStu);
                        
            //Recuperer les informations necessaires pour la convention
            InternshipCompanyModel internship = BusControl.getOffersById(BusControl.getAppById(idAppl).getInternshipID());
            COMPANYTYPE company = BusControl.getCompanybyId(3);
            STUDENTTYPE stu = BusControl.getStudentbyId(idStu);
            
            
            //Generer la convenction
            String urlConvention = BusControl.generateConvention(stu.getFIRSTNAME().toString(), stu.getLASTNAME().toString(), idStu, Appl.getCompanyName(), 3, Appl.getComMail(), Appl.getComAddress(), String.valueOf(company.getSIRET()), internship.getTitle(), internship.getDescription());
            System.out.println("URL : "+urlConvention);
            LISTIDTYPE students = BusControl.getStudentsSupervisor((int)session.getAttribute("userID"));
            List<Integer> studentsIds = students.getID();
            ArrayList<Applications> listCan= new ArrayList<>();
            
            //Changer le status de l'application => 11
            BusControl.updateApplicationStatus(11, idAppl);
            
            //Envoyer les notifications vers les actors
            BusControl.creerNotification(idStu, (int) session.getAttribute("userID"), "<a href="+urlConvention+">Your agreement of the internship " +internship.getTitle()+" for " +Appl.getCompanyName()+"</a>");
            //BusControl.creerNotification((int) session.getAttribute("userID"), (int) session.getAttribute("userID"), "<a href="+urlConvention+">Voici le lien de la convention </a>");
            BusControl.creerNotification(3, (int) session.getAttribute("userID"), "<a href="+urlConvention+">The agreement of the candidate " +stu.getFIRSTNAME().toString()+" "+stu.getLASTNAME().toString()
                    +" for the internship "+internship.getTitle()+"</a>");
            
            /*LISTIDTYPE students = BusControl.getStudentsSupervisor((int)session.getAttribute("userID"));
            List<Integer> studentsIds = students.getID();
            ArrayList<Applications> listCan= new ArrayList<>();*/

            for (Integer studId : studentsIds) {
                STUDENTTYPE stud = BusControl.getStudentbyId(studId);
                Student student = new Student(studId,(String)stud.getFIRSTNAME(), (String)stud.getLASTNAME(), (String)stud.getMAIL(), (String)stud.getPHONENUMBER(), Integer.valueOf((String)stud.getSUPERVISORID()));

                APPLICATIONTYPE listCand = getApplications(studId);
                if (listCand != null){
                    Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();

                    while (ite.hasNext()){
                        APPLICATION offer = ite.next();
                        int appId = offer.getApplicationID();
                        int status = BusControl.getAppById(appId).getStatus();

                        InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(appId).getInternshipID());

                        COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                        Applications can = new Applications(appId,student,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                                    
                        //If status est entre [8,11), on ajoute dans la liste des candidatures
                        //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                        if (status >= 8 && status <11){              
                            listCan.add(can);           
                        }
                    }
                }
            }
            
            model.addAttribute("listCan", listCan);
            Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "generateAccount", "candidatureSupervisor", model);            
            
            return "home";
        } else {
            model.addAttribute("errormessage", " You need to be authenticated. ");
            return "connection";
        }
    }
    
    /**
     * 
     * @param Appl
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/refuseSup", method = RequestMethod.GET)
    public String RefuseApplicationSup (@ModelAttribute("SpringWeb")Applications Appl, ModelMap model , HttpSession session) {
        if (session.getAttribute("userID") != null ){
            
            int idAppl = Appl.getApplicationId();
            BusControl.updateApplicationStatus(5, idAppl);
            int idStu = Appl.getStudentId();
            InternshipCompanyModel internship = BusControl.getOffersById(BusControl.getAppById(idAppl).getInternshipID());
            COMPANYTYPE company = BusControl.getCompanybyId(3);
            STUDENTTYPE stu = BusControl.getStudentbyId(idStu);
            
            LISTIDTYPE students = BusControl.getStudentsSupervisor((int)session.getAttribute("userID"));
            List<Integer> studentsIds = students.getID();
            ArrayList<Applications> listCan= new ArrayList<>();

            for (Integer studId : studentsIds) {
                STUDENTTYPE stud = BusControl.getStudentbyId(studId);
                Student student = new Student(studId,(String)stud.getFIRSTNAME(), (String)stud.getLASTNAME(), (String)stud.getMAIL(), (String)stud.getPHONENUMBER(), Integer.valueOf((String)stud.getSUPERVISORID()));

                APPLICATIONTYPE listCand = getApplications(studId);
                if (listCand != null){
                    Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();

                    while (ite.hasNext()){
                        APPLICATION offer = ite.next();


                        int appId = offer.getApplicationID();
                        int status = BusControl.getAppById(appId).getStatus();

                        InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(appId).getInternshipID());

                        COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                        Applications can = new Applications(appId,student,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                        //If status est entre [8,11), on ajoute dans la liste des candidatures
                        //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                        if (status >= 8 && status <11){              
                            listCan.add(can);           
                        }                
                    }
                }
            }
                        
            //Envoyer les notifications vers les actors
            BusControl.creerNotification(idStu, (int) session.getAttribute("userID"), "Your request for the internship "+internship.getTitle()+" of " +Appl.getCompanyName()+" is refused.");
            //BusControl.creerNotification((int) session.getAttribute("userID"), (int) session.getAttribute("userID"), "<a href="+urlConvention+">Voici le lien de la convention </a>");
            BusControl.creerNotification(3, (int) session.getAttribute("userID"), "The agreement of the candidate " +stu.getFIRSTNAME().toString()+" "+stu.getLASTNAME().toString()
                    +" for the internship "+internship.getTitle()+" is refused");
            
            model.addAttribute("listCan", listCan);
            
                        
            NOTIFSTYPE test = BusControl.getNotifications((int) session.getAttribute("userID"));
            int notifs = test.getNOTIFS().size();
            
            Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "generateAccount", "candidatureSupervisor", model);            
            
            return "home";
        } else {
            model.addAttribute("errormessage", " You need to be authenticated. ");
            return "connection";
        }
    }
}
    
